<template>

    <div class="financial-report">

        <!--时间筛选区域 -->
        <el-row :gutter="10" class="filter-section">

			<!--选择年份-->
            <el-col :span="8">
				<div>
					<span class="filter-label">选择年份</span>
					<el-select v-model="timeFilter.year" placeholder="请选择年份" size="large"style="width: 100%">
						<el-option v-for="year in availableYears" :key="year" :label="year" :value="year"></el-option>
					</el-select>
				</div>
            </el-col>

        </el-row>

        <!--查询按钮-->
        <el-button @click="SearchClick" type="primary" size="large" style="width: 100%;">
            <el-icon><Search /></el-icon>
            查询数据
        </el-button>

        <!-- 加载状态 -->
        <el-loading v-model="loading" class="loading-mask" text="正在加载财务数据..."></el-loading>

        <!--数据展示区域-->
        <div v-show="showReport" class="report-container">
            <div class="card">

				<!--报表标题展示-->
                <div class="report-header">
                    <h2 class="report-title">
                        财务分析 - {{ getPeriodDisplay() }}
                        <el-tag :type="reportData.profitStatus === 'profit' ? 'success' : 'danger'"class="status-tag">
                            {{ reportData.profitStatus === 'profit' ? '盈利' : '亏损' }}
                        </el-tag>
                    </h2>
                </div>

				<!--收入、成本、盈利卡片-->
                <div class="summary-section">

					<!--收入-->
                    <div class="summary-item">
                        <div class="item-label">总销售额</div>
                        <div class="item-value profit">{{ formatCurrency(reportData.totalSales) }}</div>
                    </div>

					<!--成本-->
                    <div class="summary-item">
                        <div class="item-label">总成本</div>
                        <div class="item-value cost">{{ formatCurrency(reportData.totalCost) }}</div>
                    </div>

					<!--盈利-->
                    <div class="summary-item profit-loss">
                        <div class="item-label">总利润</div>
                        <div class="item-value" :class="reportData.profitStatus">
                            {{ formatCurrency(reportData.totalProfit) }}
                        </div>
                    </div>
                </div>

				<!--折线图-->
				<div class="chart-container">
					<canvas id="profitChart"></canvas>
				</div>
            </div>
        </div>

        <!--空数据状态-->
        <div v-show="noDataFound" class="empty-state">
            <el-empty description="未找到对应时间段的财务数据"></el-empty>
        </div>
    </div>
</template>

<script lang="ts" setup>

// 导入必要组件
import { ref, reactive, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElNotification, ElLoading } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { Chart, registerables } from 'chart.js';
import type { TooltipItem } from 'chart.js';
Chart.register(...registerables);

// 报表折线图 ---------------------------------------------- //
let profitChart: Chart | null = null	// 利润
let XLabel = ref()
let YData = ref()

// 折线图创建和更新
function CreateChart(){

	// 清空折线图
	if (profitChart) {
    	profitChart.destroy()
	}

	// 搜索节点创建
	const ctx = document.getElementById('profitChart') as HTMLCanvasElement

	// 标签和数据
	XLabel.value = []
	for(let i = 0; i < GetSalesArray.value.length; i++){
		XLabel.value.push(`${i+1}月`)
	}

	YData.value = [
		{
			label: '收入金额',
			data: GetSalesArray.value.map(item => item.price || 0),
			backgroundColor: 'rgba(0, 0, 100, 0.6)',
			borderColor: 'rgba(0, 0, 100, 1)',
			borderWidth: 1
		},
		{
			label: '成本金额',
			data: GetCostArray.value.map(item => item.price || 0),
			backgroundColor: 'rgba(100, 0, 0, 0.6)',
			borderColor: 'rgba(100, 0, 0, 1)',
			borderWidth: 1
		},
		{
			label: '利润金额',
			data: ProfitArray.value.map(item => item.price || 0),
			backgroundColor: 'rgba(0, 100, 0, 0.6)',
			borderColor: 'rgba(0, 100, 0, 1)',
			borderWidth: 1
		},
	]

	console.log(ProfitArray)
	
	// 创建利润折线图
	profitChart = new Chart(
		ctx,
		{
			type: 'line',
    		data: {
				labels: XLabel.value,
				datasets: YData.value
			},
			options: {
				responsive: true,
				maintainAspectRatio: false,
				scales: {
					y: {
					beginAtZero: true,
					ticks: {
							callback: (value) => '¥' + value.toLocaleString()
						}
					},
				},
				plugins: {
					tooltip: {
					callbacks: {
							label: (context: TooltipItem<'bar'>) => {
								return context.dataset.label + ': ¥' + context.parsed.y.toLocaleString();
							}
						}
					}
				}
			}
		}
	)
}

// 报表折线图 end ---------------------------------------------- //

// 新的数据接受  todo.. ---------------------------------- //

// 接收的销售金额列表
// 年度查询：存入每月的销售金额
// 月度查询：存入每日的销售金额
// index标识顺序，每月就是1-12，每天就是1-30
let GetSalesArray = ref<{index: number, price?: number}[]>([])

// GET: 获取销售数据
// 传入查询日期参数

// 接收的成本呢金额列表
// 年度查询：存入每月的成本金额
// 月度查询：存入当月的成本金额
// index标识顺序，每月就是1-12，每天就是1-30
let GetCostArray = ref<{index: number, price?: number}[]>([])

// GET: 获取成本数据
// 传入查询日期参数

// 利润列表（前端计算）
let ProfitArray = ref<{index: number, price?: number}[]>([])

// 财务数据（前端计算）
const reportData = reactive({
    totalSales: 0,     // 总销售额
    totalCost: 0,      // 总成本
    totalProfit: 0,    // 总利润
    profitStatus: 'loss' as 'profit' | 'loss' // 盈亏状态
});

// 总体请求数据
async function GetFinancial(){

	// 开始加载
    loading.value = true;

	// 未找到数据的标记值否
    noDataFound.value = false;

	// 查询未完成，不显示报表
    showReport.value = false;
	
	// 请求查询
	try {
		// 构建查询参数
		let params: { year?: number; month?: number } = timeFilter.type === 'year' ? { year: timeFilter.year } : { year: timeFilter.monthYear, month: timeFilter.month };

        // 请求数据

        // 销售请求 --------------------------
		const SalesResponse = axios.get('/api/financial/sales', { params })

		// 调试输出：接收成功
		console.log((await SalesResponse).data.data)

		// 赋值
		GetSalesArray.value = (await SalesResponse).data.data || []

		// 调试输出：赋值
		console.log(GetSalesArray.value)

        // 成本请求 --------------------------
		const CostResponse = axios.get('/api/financial/cost', { params })

		// 调试输出：接收成功
		console.log((await CostResponse).data.data)

		// 赋值
		GetCostArray.value = (await CostResponse).data.data || []

		// 调试输出：赋值
		console.log(GetCostArray.value)

        // 处理数据，求和汇总到各个表中

		// 销售金额数组和成本金额数组的长度应该一样
		if(GetSalesArray.value.length != GetCostArray.value.length){
			ElNotification.success({ message: '数据获取出错，请核对' })
			return
		}

		// 清空财务数据表
		reportData.totalCost = 0
		reportData.totalSales = 0
		reportData.totalProfit = 0

		// 清空利润数据
		ProfitArray.value = []

		// 利润数组计算
		let CurSalesPrice = 0
		let CurCostPrice = 0
		let CurProfitPrice = 0
		for(let i = 0; i < GetSalesArray.value.length; i++){

			// 计算利润
			CurSalesPrice = GetSalesArray.value[i].price || 0
			CurCostPrice = GetCostArray.value[i].price || 0
			CurProfitPrice = CurSalesPrice - CurCostPrice
			console.log(CurSalesPrice, CurCostPrice, CurProfitPrice)

			// 插入利润数据
			ProfitArray.value.push({index: GetCostArray.value[i].index, price: CurProfitPrice})

			// 求和计算
			reportData.totalCost += CurCostPrice
			reportData.totalSales += CurSalesPrice
			reportData.totalProfit += CurProfitPrice
		}

		// 盈利状态判断
        reportData.profitStatus = reportData.totalProfit >= 0 ? 'profit' : 'loss';

		// 获取和处理完毕，打开报表
        showReport.value = true;

		// 如果没有销售和成本，就是没有查询到数据，显示空页面
        noDataFound.value = (reportData.totalSales === 0 && reportData.totalCost === 0);
        
		// 成功提示
		ElNotification.success({ message: '财务数据获取成功' });

		// 画图
		CreateChart()
    } catch (error) {
        console.error('数据加载失败:', error);
        ElNotification.error({ message: '获取财务数据失败，请重试' });
        showReport.value = false;
    } finally {
		loading.value = false;
    }
}

// 查询回调
function SearchClick(){

	if (timeFilter.type === 'year' && !timeFilter.year) {
        ElNotification.error({ message: '请选择年份' });
        return;
    }
	GetFinancial()
}

// 新的数据接受  todo.. end ---------------------------------- //

// 状态管理
const loading = ref(false);
const showReport = ref(false);
const noDataFound = ref(false);

// 时间选择记录
const timeFilter = reactive({
    type: 		'year',
    year: 		undefined,
    monthYear: 	undefined,
    month: 		undefined
});

// 可用年份（最近3年 + 当年）
const availableYears = computed(() => {
    const currentYear = new Date().getFullYear();
    return [currentYear - 2, currentYear - 1, currentYear, currentYear + 1];
});

// 可用月份
const availableMonths = computed(() => {
    return Array.from({ length: 12 }, (_, i) => i + 1);
});

// 格式化货币
const formatCurrency = (value: number) => {
    return `¥ ${value.toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    })}`;
};

// 获取时间段显示文本
const getPeriodDisplay = () => {
    if (timeFilter.type === 'year') {
        return `${timeFilter.year}年`;
    } else if (timeFilter.type === 'month') {
        return `${timeFilter.monthYear}年${timeFilter.month}月`;
    }
    return '';
};

</script>

<style scoped class="financial-report">

.filter-section {
    margin-bottom: 20px;
}

.filter-label {
    color: #666;
    font-size: 14px;
    margin-right: 10px;
}

.month-filter {
    margin-bottom: 10px;
}

.report-container {
    margin-top: 20px;
}

.card {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.05);
}

.report-header {
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 15px;
    margin-bottom: 20px;
}

.report-title {
    font-size: 18px;
    font-weight: 500;
    margin: 0;
}

.status-tag {
    margin-left: 10px;
    font-size: 14px;
}

.summary-section {
    display: flex;
    justify-content: space-around;
    padding: 20px 0;
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
}

.summary-item {
    text-align: center;
    flex: 1;
}

.item-label {
    color: #999;
    font-size: 14px;
    margin-bottom: 8px;
}

.item-value {
    font-size: 22px;
    font-weight: 600;
}

.item-value.profit {
    color: #4CAF50;
}

.item-value.cost {
    color: #2196F3;
}

.item-value.loss {
    color: #FF4444;
}

.loading-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255,255,255,0.9);
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: center;
}

.empty-state {
    margin-top: 30px;
    text-align: center;
}

.chart-container {
	height: 300px;
	margin-top: 20px;
}

</style>    